package alit.generator.bl.generator;

import alit.generator.bl.generator.exception.GeneratorException;
import alit.generator.bl.populator.IPopulator;

import java.util.ArrayList;
import java.util.List;

/**
 * User: Alexander Litvinenko
 * Date: 11/22/11
 * Time: 7:22 PM
 */
public class DataGenerator {
    Context context = new Context();
    List<ColumnDesc> descList = new ArrayList<ColumnDesc>();
    private int rowCount = 20;

    public void registerColumn(String name, IPopulator populator) {
        for (ColumnDesc desc : descList) {
            if (desc.getName().equals(name)) {
                throw new GeneratorException(String.format("Column name '%s' already exists", name));
            }
        }
        descList.add(new ColumnDesc(name, populator));
        context.getTable().createColumn(name, getRowCount());
    }

    public String generate() {

        for (int i = 0; i < rowCount; i++) {
            context.setCurrentRow(i);
            for (ColumnDesc desc : descList) {
                context.setCurrentColumnName(desc.getName());
                context.getTable().setCell(desc.getName(), i, desc.getPopulator().populate(context));
            }
        }
        String columns = "";
        for (ColumnDesc desc : descList) {
            columns += String.format("'%s', ", desc.getName());
        }
        columns = columns.substring(0, columns.length() - 2);
        String values = "";
        for (int i = 0; i < rowCount; i++) {
            values += "\t,(";
            for (ColumnDesc desc : descList) {
                values += context.getTable().getCell(desc.getName(), i) + ", ";
            }
            values = values.substring(0, values.length() - 2) + ")\n";
        }
        values = "\t " + values.substring(2);

        return String.format("INSERT INTO %s(%s) VALUES\n%s", context.getTableName(), columns, values);
    }


    public void setTableName(String tableName) {
        context.setTableName(tableName);
    }

    public int getRowCount() {
        return rowCount;
    }

    public void setRowCount(int rowCount) {
        this.rowCount = rowCount;
    }

    public static class ColumnDesc {
        private String name;
        private IPopulator populator;

        public ColumnDesc(String name, IPopulator populator) {
            this.name = name;
            this.populator = populator;
        }

        public IPopulator getPopulator() {
            return populator;
        }

        public String getName() {
            return name;
        }
    }
}
